import React from "react";

// 声明状态
type Istate = {
    content: string
    isVip: boolean
}
class Clipboard extends React.Component<any,Istate> {
    constructor(props:any){
        super(props);
        this.state = {
           content: '',
           isVip:false
        }
    }
    // 点击事件
    handleClick = (e:React.MouseEvent) => {
        console.log(e.nativeEvent); // 获取dom原生的event事件
    }

    // 按下事件
    handleKeyDown = (e:React.ClipboardEvent) => {
        console.log(e);
        
    }

    // 复制事件
    handleCopy = () => {
        if(!this.state.isVip){
            alert('请先充值Vip,再进行复制')
            return
        }
        // 获取被选中的内容
        let sel:string | undefined = window.getSelection()?.toString();
        // console.log(sel);
        // 写入到剪贴板
        navigator.clipboard.writeText(sel!)
    }

    // 粘贴事件
    handlePaste = () => {
        if(!this.state.isVip){
            alert('请先充值Vip,再进行粘贴')
            return
        }
        // 从剪贴板读取
        navigator.clipboard.readText()
        .then((text:string) => {
            console.log(text); 
            this.setState({content:text})
        })
    }

    componentDidMount():void {
        // 阻止Ctrl+C,V默认行为
        document.onkeydown = function(e:Event){
            e.preventDefault();
        }
        // 阻止鼠标右击默认行为
        document.oncontextmenu = function(e:Event){
            e.preventDefault();
        }
    }

    // 充值vip
    handleCharge = () => {
        this.setState({
            isVip:true
        })
        alert('充值成功')
    }
    render(): React.ReactNode {
        return(
            <fieldset>
                <legend>剪贴板事件</legend>
                <button onClick={this.handleClick}>点击</button>
                {/* onCut:剪切事件 ; onCopy:复制事件 ; onPaste: 粘贴事件*/}
                <input type="text" onPaste={this.handleKeyDown}/>
                <p>花有重开日，人无再少年</p>
                <div contentEditable suppressContentEditableWarning={true} style={{height:'50px',border: '1px solid #ccc'}}>
                    {this.state.content}
                </div>
                <button onClick={this.handleCopy}>复制</button>
                <button onClick={this.handlePaste}>粘贴</button>
                <button style={{backgroundColor:'red'}} onClick={this.handleCharge}>充值vip</button>
                <button onClick={() => {
                    this.setState({
                        isVip: false
                    })
                    alert('退款成功')
                }}>退钱</button>
            </fieldset>
        )
    }
}

export default Clipboard